import React, { useState, useEffect, useContext, useRef } from "react";
import {
  Box,
  VStack,
  HStack,
  Text,
  Button,
  Select,
  Flex,
  Badge,
  useColorModeValue,
  IconButton,
  Menu,
  MenuButton,
  MenuList,
  MenuItem,
  Image,
  Input,
  useToast,
  Tooltip,
} from "@chakra-ui/react";
import {
  ChevronDownIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  SettingsIcon,
  RepeatIcon,
} from "@chakra-ui/icons";
import { motion } from "framer-motion";
import { MainContext } from "@/src/providers/MainProvider";
import { useTranslation } from "@/src/i18n";
// 动画组件
const MotionBox = motion(Box);
const MotionVStack = motion(VStack);

function HomePage() {
  const { changeLanguage, i18n } = useTranslation("common");
  const [currentDeviceIndex, setCurrentDeviceIndex] = useState(0);
  const [videoError, setVideoError] = useState(false);
  const [backgroundType, setBackgroundType] = useState<"video" | "image">(
    "video"
  );
  const [customBackground, setCustomBackground] = useState<string>("");
  const [isBackgroundMenuOpen, setIsBackgroundMenuOpen] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const toast = useToast();
  const { connectKeyboard, t } = useContext(MainContext);

  // 模拟设备数据
  const devices = [
    {
      id: 1,
      name: t("80"),
      model: t("81"),
      image: "/products/keyboard-m81.png",
      status: "disconnected",
      battery: 85,
      connectionType: "wireless",
    },
    {
      id: 2,
      name: t("80"),
      model: t("81"),
      image: "/products/keyboard-m81.png",
      status: "disconnected",
      battery: 92,
      connectionType: "usb",
    },
  ];

  // 加载保存的背景设置
  useEffect(() => {
    const savedBackgroundType = localStorage.getItem("homeBackgroundType");
    const savedCustomBackground = localStorage.getItem("homeCustomBackground");

    if (savedBackgroundType) {
      setBackgroundType(savedBackgroundType as "video" | "image");
    }
    if (savedCustomBackground) {
      setCustomBackground(savedCustomBackground);
    }
  }, []);

  // 保存背景设置到localStorage
  const saveBackgroundSettings = (
    type: "video" | "image",
    customBg?: string
  ) => {
    localStorage.setItem("homeBackgroundType", type);
    if (customBg) {
      localStorage.setItem("homeCustomBackground", customBg);
    }
  };

  const currentDevice = devices[currentDeviceIndex];

  const handleConnect = () => {
    connectKeyboard([{ usagePage: 0xff00, usage: 0x0001 }]);
  };

  const nextDevice = () => {
    setCurrentDeviceIndex((prev) => (prev + 1) % devices.length);
  };

  const prevDevice = () => {
    setCurrentDeviceIndex(
      (prev) => (prev - 1 + devices.length) % devices.length
    );
  };

  // 处理视频加载错误
  const handleVideoError = () => {
    console.log("视频加载失败，切换到静态背景");
    setVideoError(true);
  };

  // 处理文件选择
  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // 检查文件类型
      if (!file.type.startsWith("image/")) {
        toast({
          title: t("800"),
          description: t("801"),
          status: "error",
          duration: 3000,
          isClosable: true,
        });
        return;
      }

      // 检查文件大小 (限制为5MB)
      if (file.size > 5 * 1024 * 1024) {
        toast({
          title: t("802"),
          description: t("803"),
          status: "error",
          duration: 3000,
          isClosable: true,
        });
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        const imageUrl = e.target?.result as string;
        setCustomBackground(imageUrl);
        setBackgroundType("image");
        saveBackgroundSettings("image", imageUrl);
        setIsBackgroundMenuOpen(false);
      };
      reader.readAsDataURL(file);
    }
  };

  // 重置为默认视频背景
  const resetToVideoBackground = () => {
    setBackgroundType("video");
    saveBackgroundSettings("video");
    setIsBackgroundMenuOpen(false);
  };

  // 打开文件选择器
  const openFileSelector = () => {
    fileInputRef.current?.click();
  };

  return (
    <Box minH="100vh" position="relative" overflow="hidden">
      {/* 隐藏的文件输入 */}
      <Input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileSelect}
        style={{ display: "none" }}
      />

      {/* 背景区域 */}
      <Box position="absolute" top={0} left={0} w="100%" h="100%" zIndex={0}>
        {backgroundType === "video" && !videoError ? (
          <video
            autoPlay
            loop
            muted
            playsInline
            style={{
              position: "absolute",
              top: "50%",
              left: "50%",
              minWidth: "100%",
              minHeight: "100%",
              width: "auto",
              height: "auto",
              transform: "translate(-50%, -50%)",
              objectFit: "cover",
            }}
            onError={handleVideoError}
          >
            <source src="/home.mp4" type="video/mp4" />
          </video>
        ) : (
          <Box
            position="absolute"
            top={0}
            left={0}
            w="100%"
            h="100%"
            style={{
              backgroundImage:
                backgroundType === "image" && customBackground
                  ? `url(${customBackground})`
                  : "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
              backgroundSize: "cover",
              backgroundPosition: "center",
              backgroundRepeat: "no-repeat",
            }}
          />
        )}
      </Box>

      {/* 主要内容容器 */}
      <Box
        position="relative"
        zIndex={1}
        minH="100vh"
        style={{
          backdropFilter: "blur(2px)",
          WebkitBackdropFilter: "blur(2px)",
        }}
      >
        {/* 顶部工具栏 */}
        <Flex justify="flex-end" align="center" p={6}>
          <HStack spacing={4}>
            {/* 切换皮肤按钮 */}
            <Menu
              isOpen={isBackgroundMenuOpen}
              onClose={() => setIsBackgroundMenuOpen(false)}
            >
              <MenuButton
                as={Button}
                size="sm"
                onClick={() => setIsBackgroundMenuOpen(!isBackgroundMenuOpen)}
                style={{
                  background: "rgba(255, 255, 255, 0.6)",
                  backdropFilter: "blur(10px)",
                  WebkitBackdropFilter: "blur(10px)",
                  border: "1px solid rgba(255, 165, 0, 0.2)",
                  color: "rgb(15, 23, 42)",
                  fontWeight: "500",
                }}
                _hover={{
                  background: "rgba(255, 255, 255, 0.8)",
                  borderColor: "rgba(255, 165, 0, 0.3)",
                  transform: "translateY(-1px)",
                  boxShadow: "0 4px 12px rgba(255, 165, 0, 0.15)",
                }}
                _active={{
                  background: "rgba(255, 255, 255, 0.9)",
                  transform: "translateY(0)",
                }}
              >
                <HStack spacing={2}>
                  <Box as="span" fontSize="16px">
                    🎨
                  </Box>
                  <Text fontSize="sm">{t("804")}</Text>
                </HStack>
              </MenuButton>
              <MenuList
                style={{
                  background: "rgba(255, 255, 255, 0.9)",
                  backdropFilter: "blur(20px)",
                  WebkitBackdropFilter: "blur(20px)",
                  border: "1px solid rgba(255, 165, 0, 0.2)",
                  borderRadius: "12px",
                  boxShadow: "0 8px 32px rgba(255, 165, 0, 0.15)",
                  minWidth: "200px",
                }}
              >
                <MenuItem
                  onClick={openFileSelector}
                  style={{
                    background: "transparent",
                    color: "rgb(15, 23, 42)",
                    padding: "12px 16px",
                  }}
                  _hover={{
                    background: "rgba(255, 165, 0, 0.1)",
                  }}
                >
                  <HStack spacing={3}>
                    <Box as="span" fontSize="16px">
                      🖼️
                    </Box>
                    <Text>{t("805")}</Text>
                  </HStack>
                </MenuItem>
                <MenuItem
                  onClick={resetToVideoBackground}
                  style={{
                    background: "transparent",
                    color: "rgb(15, 23, 42)",
                    padding: "12px 16px",
                  }}
                  _hover={{
                    background: "rgba(255, 165, 0, 0.1)",
                  }}
                >
                  <HStack spacing={3}>
                    <RepeatIcon />
                    <Text>{t("806")}</Text>
                  </HStack>
                </MenuItem>
              </MenuList>
            </Menu>

            {/* 语言切换 */}
            <Menu>
              <MenuButton
                as={Button}
                rightIcon={<ChevronDownIcon />}
                size="sm"
                style={{
                  background: 'rgba(255, 255, 255, 0.6)',
                  backdropFilter: 'blur(10px)',
                  WebkitBackdropFilter: 'blur(10px)',
                  border: '1px solid rgba(255, 165, 0, 0.2)',
                  color: 'rgb(15, 23, 42)',
                  fontWeight: '500'
                }}
                _hover={{
                  background: 'rgba(255, 255, 255, 0.8)',
                  borderColor: 'rgba(255, 165, 0, 0.3)',
                  transform: 'translateY(-1px)',
                  boxShadow: '0 4px 12px rgba(255, 165, 0, 0.15)'
                }}
                _active={{
                  background: 'rgba(255, 255, 255, 0.9)',
                  transform: 'translateY(0)'
                }}
              >
                <HStack spacing={2}>
                  <Box
                    w="16px"
                    h="16px"
                    borderRadius="full"
                    style={{
                      background: 'linear-gradient(135deg, rgba(255, 165, 0, 0.8) 0%, rgba(255, 140, 0, 0.8) 100%)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: '8px',
                      color: 'white',
                      fontWeight: 'bold'
                    }}
                  >
                    🌐
                  </Box>
                  <Text fontSize="sm">{i18n.language === 'cn' ? '中文' : 'English'}</Text>
                </HStack>
              </MenuButton>
              <MenuList
                style={{
                  background: 'rgba(255, 255, 255, 0.9)',
                  backdropFilter: 'blur(20px)',
                  WebkitBackdropFilter: 'blur(20px)',
                  border: '1px solid rgba(255, 165, 0, 0.2)',
                  borderRadius: '12px',
                  boxShadow: '0 8px 32px rgba(255, 165, 0, 0.15)'
                }}
              >
                <MenuItem 
                  onClick={() => changeLanguage('cn')}
                  style={{
                    background: 'transparent',
                    color: 'rgb(15, 23, 42)'
                  }}
                  _hover={{
                    background: 'rgba(255, 165, 0, 0.1)'
                  }}
                >
                  中文
                </MenuItem>
                <MenuItem 
                  onClick={() => changeLanguage('en')}
                  style={{
                    background: 'transparent',
                    color: 'rgb(15, 23, 42)'
                  }}
                  _hover={{
                    background: 'rgba(255, 165, 0, 0.1)'
                  }}
                >
                  English
                </MenuItem>
              </MenuList>
            </Menu>
          </HStack>
        </Flex>

        {/* 主内容区域 */}
        <VStack spacing={12} align="center" px={8} pb={12}>
          {/* 标题区域 */}
          <MotionVStack
            spacing={4}
            textAlign="center"
            initial={{ opacity: 0, y: -30 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, ease: "easeOut" }}
          >
            <Text
              fontSize={{ base: "3xl", md: "5xl", lg: "6xl" }}
              fontWeight="800"
              style={{
                background:
                  "linear-gradient(135deg, rgb(255, 140, 0) 0%, rgb(255, 165, 0) 50%, rgb(255, 180, 0) 100%)",
                WebkitBackgroundClip: "text",
                WebkitTextFillColor: "transparent",
                backgroundClip: "text",
                textShadow: "0 4px 8px rgba(255, 165, 0, 0.2)",
              }}
              letterSpacing="-0.02em"
            >
              {t("9")}
            </Text>
            <Text
              fontSize={{ base: "lg", md: "xl" }}
              color="rgb(71, 85, 105)"
              fontWeight="500"
              maxW="600px"
              lineHeight="1.6"
            >
              {t("810")}
            </Text>
          </MotionVStack>

          {/* 设备展示区域 */}
          <MotionBox
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.8, delay: 0.3 }}
            w="full"
            maxW="800px"
          >
            <Box
              style={{
                background: "rgba(255, 255, 255, 0.6)",
                backdropFilter: "blur(20px)",
                WebkitBackdropFilter: "blur(20px)",
                borderRadius: "24px",
                padding: "32px",
                border: "1px solid rgba(255, 165, 0, 0.2)",
                boxShadow: "0 8px 32px rgba(255, 165, 0, 0.1)",
              }}
            >
              {/* 设备轮播控制 */}
              <Flex justify="space-between" align="center" mb={8}>
                <IconButton
                  aria-label="Previous device"
                  icon={<ChevronLeftIcon />}
                  onClick={prevDevice}
                  size="lg"
                  style={{
                    background: "rgba(255, 255, 255, 0.8)",
                    border: "1px solid rgba(255, 165, 0, 0.3)",
                    color: "rgb(255, 140, 0)",
                  }}
                  _hover={{
                    background: "rgba(255, 165, 0, 0.1)",
                    transform: "translateX(-2px)",
                    boxShadow: "0 4px 12px rgba(255, 165, 0, 0.2)",
                  }}
                  borderRadius="full"
                />

                <VStack spacing={4} flex={1} mx={8}>
                  <Text
                    fontSize="2xl"
                    fontWeight="700"
                    color="rgb(15, 23, 42)"
                    textAlign="center"
                  >
                    {currentDevice.name}
                  </Text>

                  <HStack spacing={4} justify="center">
                    <Badge
                      style={{
                        background: "rgba(255, 165, 0, 0.15)",
                        color: "rgb(255, 140, 0)",
                        padding: "4px 12px",
                        borderRadius: "20px",
                        fontSize: "12px",
                        fontWeight: "600",
                        border: "1px solid rgba(255, 165, 0, 0.3)",
                      }}
                    >
                      {currentDevice.model}
                    </Badge>
                  </HStack>
                </VStack>

                <IconButton
                  aria-label="Next device"
                  icon={<ChevronRightIcon />}
                  onClick={nextDevice}
                  size="lg"
                  style={{
                    background: "rgba(255, 255, 255, 0.8)",
                    border: "1px solid rgba(255, 165, 0, 0.3)",
                    color: "rgb(255, 140, 0)",
                  }}
                  _hover={{
                    background: "rgba(255, 165, 0, 0.1)",
                    transform: "translateX(2px)",
                    boxShadow: "0 4px 12px rgba(255, 165, 0, 0.2)",
                  }}
                  borderRadius="full"
                />
              </Flex>

              {/* 设备图片 */}
              <Flex justify="center" mb={8}>
                <Box
                  style={{
                    background: "rgba(255, 255, 255, 0.5)",
                    borderRadius: "20px",
                    padding: "24px",
                    border: "1px solid rgba(255, 165, 0, 0.2)",
                    backdropFilter: "blur(10px)",
                    WebkitBackdropFilter: "blur(10px)",
                  }}
                >
                  <Image
                    src={currentDevice.image}
                    alt={currentDevice.name}
                    style={{
                      width: "300px",
                      height: "200px",
                      objectFit: "contain",
                      filter: "drop-shadow(0 4px 8px rgba(255, 165, 0, 0.1))",
                    }}
                  />
                </Box>
              </Flex>

              {/* 连接按钮 */}
              <Flex justify="center">
                <Button
                  size="lg"
                  loadingText={t("811")}
                  onClick={handleConnect}
                  style={{
                    background:
                      "linear-gradient(135deg, rgb(255, 140, 0) 0%, rgb(255, 165, 0) 100%)",
                    color: "white",
                    fontWeight: "600",
                    fontSize: "16px",
                    padding: "12px 32px",
                    borderRadius: "16px",
                    border: "none",
                    boxShadow: "0 4px 16px rgba(255, 165, 0, 0.3)",
                    minWidth: "160px",
                  }}
                  _hover={{
                    background:
                      "linear-gradient(135deg, rgb(255, 120, 0) 0%, rgb(255, 145, 0) 100%)",
                    transform: "translateY(-2px)",
                    boxShadow: "0 6px 20px rgba(255, 165, 0, 0.4)",
                  }}
                  _active={{
                    transform: "translateY(0)",
                    boxShadow: "0 2px 8px rgba(255, 165, 0, 0.3)",
                  }}
                >
                  {t("812")}
                </Button>
              </Flex>
            </Box>
          </MotionBox>

          {/* 底部信息 */}
          <MotionBox
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, delay: 0.6 }}
            textAlign="center"
          >
            <Text fontSize="sm" color="rgb(100, 116, 139)" fontWeight="500">
              {t("813")}
            </Text>
          </MotionBox>
        </VStack>
      </Box>
    </Box>
  );
}

export default HomePage;
